package org.song.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.song.annotation.PowerEquals;
import org.song.annotation.RequestTimeRecord;
import org.song.exception.result.AjaxResult;
import org.song.model.entity.ImgResult;
import org.song.service.cache.CaptchaRedisCacheService;
import org.song.util.CaptchaUtil;
import org.song.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.awt.image.BufferedImage;

@Api(tags = {"验证码"})
@Controller
@RequestMapping(value = "/captcha")
public class CaptchaController {

    @Autowired( required = true )
    @Qualifier( value = "captchaRedisCacheServiceImpl")
    private CaptchaRedisCacheService captchaRedisCacheService;

    /**
     * 获取验证码
     * @return
     */
    @PowerEquals
    @RequestTimeRecord
    @ApiOperation(value = "获取验证码" , notes = "获取验证码")
    @ResponseBody
    @RequestMapping(value = "/getCaptcha" , method = RequestMethod.GET)
    public AjaxResult<ImgResult> getCaptcha() {
        // 使用验证码生成工具类生成base64加密后的验证码
        final CaptchaUtil captchaUtil = new CaptchaUtil();
        final BufferedImage image = captchaUtil.getImage();
        final String base64 = CaptchaUtil.getBase64(image);
        final String code = captchaUtil.getCode();
        final String uuId = UUIDUtil.getUUIDString();
       captchaRedisCacheService.saveCaptcha( uuId ,code );
        if ( null != base64 ) {
            return AjaxResult.success(ImgResult.builder().img(base64).imgCode(code).imgId(uuId).build());
        }
        return AjaxResult.failed("图片验证码获取失败");
    }
}
